package com.solution.admin.auth.filter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.solution.admin.auth.constants.AuthConstants;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.utils.StringUtils;

/**
 * 登录终端类型过滤器(暂时无用)
 * @author llp
 */
public class LoginTerminalFilter implements Filter  {

	@Override
	public void destroy() {
	}

	/**
	 * 判断微信端、pc端、管理后台
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		// 未登录情况下进行拦截，存储是访问来源
		Subject currentUser = SecurityUtils.getSubject();
		if(!currentUser.isAuthenticated()){
			// 静态资源不进行拦截
			String[] staticUrls = PublicConfigUtil.readConfig("statics.url").split(",");
			String requestPath = req.getServletPath();
			if(StringUtils.endsWithAny(requestPath, staticUrls)){
				chain.doFilter(request, response);
				return;
			}
			ServletContext sc = req.getSession().getServletContext();
	        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
	        
	        // shiro不拦截地址，该filter也不拦截
	        String shiroFilterUrls = (String)cxt.getBean("shiroFilterChainDefinitions");
	        String[] filterUrls = shiroFilterUrls.split("\n\t\t\t\t");
	        if(filterUrls != null && filterUrls.length> 0){
	        	for(String url : filterUrls){
	        		String[] tmpUrl = url.split("=");
	        		if(tmpUrl != null && tmpUrl.length == 2){
	        			String urlName = tmpUrl[0].replace("**", "").trim();
	        			String urlAuth = tmpUrl[1].trim();
	        			if( requestPath.contains(urlName)&& "anon".equals(urlAuth)){
		        			chain.doFilter(request, response);
		        			return;
		        		}
	        		}
	        		
	        	}
	        }
	        // 标记存储在redis中
	        RedisTemplate template = (RedisTemplate)cxt.getBean("redisTemplate");
	        BoundValueOperations options = template.boundValueOps("LOGIN_TERMINAL"+req.getSession().getId().substring(12));
	        options.expire(30, TimeUnit.MINUTES);
			String userAgent = req.getHeader("user-agent").toLowerCase();
			if(userAgent.indexOf("micromessenger")>-1){
				//微信客户端
				options.set(AuthConstants.LOGIN_TERMINAL_TYPE.WX.getCode());
			}else{
				// 判断是pc前端还是后台
				if(requestPath.startsWith("/pc")){
					options.set(AuthConstants.LOGIN_TERMINAL_TYPE.PC.getCode());
				}else{
					options.set(AuthConstants.LOGIN_TERMINAL_TYPE.BACKEND.getCode());
				}
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
